#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

SListNode* BuySListNode(SListDataType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		perror("mailoc fail");
		return NULL;
	}

	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}

void SLTPushBack(SListNode** pphead, SListDataType x)
{
	assert(pphead);
	SListNode* newnode = BuySListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SListNode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
	
}

void SLTPrint(SListNode* phead)
{
	SListNode* cur = phead;
	while (cur)
	{
		printf("%d->",cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPopBack(SListNode** pphead)
{
	assert(pphead);
	if (*pphead == NULL)
	{
		return;
	}
	else if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SListNode* prev = NULL;
		SListNode* tail = *pphead;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;
		prev->next = NULL;
	}
}

void SLTPushFront(SListNode** pphead, SListDataType x)
{
	assert(pphead);
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SLTPopFront(SListNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SListNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}

SListNode* SLTFindNode(SListNode* phead, SListDataType x)
{
	SListNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsertAfter(SListNode* pos, SListDataType x)
{
	assert(pos);
	SListNode* newnode = BuySListNode(x);
	SListNode* next = pos->next;
	pos->next = newnode;
	newnode->next = next;

}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	SListNode* nextNext = pos->next->next;
	SListNode* next = pos->next;
	pos->next = nextNext;
	free(next);
	next = NULL;
}

void SLTInsert(SListNode** pphead, SListNode* pos, SListDataType x)
{
	assert(pphead);
	assert(pos);
	SListNode* newnode = BuySListNode(x);
	SListNode* prev = *pphead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	prev->next = newnode;
	newnode->next = pos;

}

void SLTErase(SListNode** pphead, SListNode* pos)
{
	SListNode* prev = *pphead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}

	SListNode* next = pos->next;
	prev->next = next;
	free(pos);
	pos = NULL;

}

void SLTDestroy(SListNode** pphead)
{
	assert(pphead);
	SListNode* cur,* next= *pphead;
	while (cur)
	{
		next = cur->next;
		free(cur);
		cur = next;
		*pphead = cur;
	}
	*pphead = NULL;
}